
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
import requests
import json
import datetime


class Ali_DDNS():
    def __init__(self):
        self.get_ip_url = 'http://ip.taobao.com/service/getIpInfo2.php?ip=myip'     # 外网IP查询
        self.domain_name = 'xxxx.xxx'      # 要解析的域名
        self.accessKeyId = 'xxxxxxxxxxxxxxxxxxxx'       # 密钥
        self.accessSecret = 'xxxxxxxxxxxxxxxxxxxx'        # 密钥
        self.RegionId = 'cn-hangzou'       # 标识

    def get_my_ip(self):        # 获取外网IP
        return json.loads(requests.get(self.get_ip_url).content)['data']['ip']

    def get_analysis_list(self, domain):        # 获取解析列表
        client = AcsClient(self.accessKeyId, self.accessSecret, self.RegionId)
        request = DescribeDomainRecordsRequest()
        request.set_accept_format('json')
        request.set_DomainName(domain)
        try:
            response = client.do_action_with_exception(request)
            return json.loads(response)
        except ClientException as e:
            return e

    def update_record(self, recordId, value, rr):       # 更新解析地址
        client = AcsClient(self.accessKeyId, self.accessSecret, self.RegionId)
        request = UpdateDomainRecordRequest()
        request.set_accept_format('json')
        request.set_RecordId(recordId)
        request.set_RR(rr)
        request.set_Type("A")
        request.set_Value(value)
        try:
            response = client.do_action_with_exception(request)
            return json.loads(response)
        except ServerException as e:
            return e

    def analyze_data(self, data):       # 分析数据
        data, analyze_list = data['DomainRecords']['Record'], []
        for x in data:
            dict_data = {}
            if '@' == x['RR'] or 'www' == x['RR']:
                dict_data['RR'], dict_data['Value'], dict_data['RecordId'] = x['RR'], x['Value'], x['RecordId']
                analyze_list.append(dict_data)
        return analyze_list

    def written_records(self, data):        # 写入日志
        data = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '>>' + data
        with open('./message.log', 'a') as f:
            f.write(data)
            f.close()

    def main(self):     # 主脚本
        response = self.get_analysis_list(self.domain_name)
        if type(response) == dict:
            data_list = self.analyze_data(response)
            ip = self.get_my_ip()
            for x in data_list:
                response = self.update_record(x['RecordId'], ip, x['RR'])
                if type(response) == dict:
                    data = '已成功将 %s 的%s记录值由原来的%s修改为现在的%s' % (self.domain_name, x['RR'], x['Value'], ip)
                    self.written_records(data)
                else:
                    print('错误信息:', response)
        else:
            print('错误信息:', response)


if __name__ == '__main__':
    abc = Ali_DDNS()
    abc.main()



